package org.example.cloud.service.implementation;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.permission.FsPermission;
import org.example.cloud.bean.File;
import org.example.cloud.bean.Folder;
import org.example.cloud.controller.LoginController;
import org.example.cloud.mapper.FileFolderMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;
import java.util.List;

@Service
public class FileFolderImpl implements FileFolderService{

    @Autowired
    private FileFolderMapper fileFolderMapper;
    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
    @Override
    public List<Folder> getFolders(String username) {
        String path = "/user/"+username;
        return fileFolderMapper.findFoldersByUsernameAndPath(username, path);
    }

    @Override
    public List<File> getFiles(String username) {
        String path = "/user/"+username;
        logger.debug("path:",path );
        List<File> files = fileFolderMapper.findFilesByUsernameAndPath(username, path);

        // 获取文件类型并设置到 File 对象中
        for (File file : files) {
            String fileType = fileFolderMapper.findFileTypeById(file.getTypeId());
            file.setType(fileType);
        }

        return files;
    }
    @Override
    public void initFolder(String username) throws IOException {
        Configuration conf = new Configuration();
        FileSystem fs = FileSystem.get(conf);

        Path userDir = new Path("/user/" + username+"/");
        if (!fs.exists(userDir)) {
            fs.mkdirs(userDir); // 创建用户根目录

            // 创建默认子目录
            String[] defaultDirs = {"Documents", "Pictures", "Videos","Audios","Others"};
            for (String dir : defaultDirs) {
                fs.mkdirs(new Path(userDir, dir));
            }
        }
    }

    @Override
    public boolean createFolder(String username, String parentPath, String dirName){
        FileSystem fs = null;
        try {
            fs = FileSystem.get(new Configuration());
            fs.setWriteChecksum(false);
            //Integer parentId = fileFolderMapper.findParentId(parentPath);
            // 验证父目录是否存在
            logger.debug("path:",parentPath );
            Path parentDir = new Path("/user/" + username + "/" + parentPath);
            logger.debug("parentDir:",parentDir );
            if (!fs.exists(parentDir)) {
                throw new IOException("Parent directory does not exist");
            }

            // 创建新目录
            Path newDir = new Path(parentDir, dirName);

            if (fs.exists(newDir)) {
                return false; // 目录已存在
            }
            // 创建目录并设置权限
            boolean success = fs.mkdirs(newDir);
            if (success) {
                fs.setPermission(newDir, FsPermission.valueOf("drwxr-xr-x"));
                // 保存目录信息到数据库
                fileFolderMapper.saveFolder(dirName,newDir.toString(),username, new Date());
            }
            return success;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            if (fs != null) {
                try {
                    fs.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public boolean deleteFolder(String username, String folderPath) {
        FileSystem fs = null;
        try {
            Configuration conf = new Configuration();
            fs = FileSystem.get(conf);

            // 获取文件夹的 ID
            Integer folderId = fileFolderMapper.findParentId(folderPath);
            if (folderId == null) {
                throw new IOException("Folder not found");
            }

            // 标记文件夹为已删除
            boolean success = fileFolderMapper.moveFolderToTrash(folderId, new Date());
            if (success) {
                // 可选：从 HDFS 中删除文件夹
                Path folder = new Path(folderPath);
                fs.delete(folder, true); // true 表示递归删除
            }

            return success;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            if (fs != null) {
                try {
                    fs.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public boolean deleteFile(String username, String filePath) {
        FileSystem fs = null;
        try {
            // 假获取文件 ID
            Integer fileId = fileFolderMapper.getFileId(filePath);
            if (fileId == null) {
                throw new IOException("File not found");
            }
            // 标记文件为已删除
            boolean success = fileFolderMapper.moveFileToTrash(fileId, new Date());
            if (success) {
                // 可选：从 HDFS 中删除文件
                Path file = new Path(filePath);
                fs.delete(file, false); // false 表示不递归删除
                fs.close();
            }

            return success;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            if (fs != null) {
                try {
                    fs.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
